import axios from 'axios'
import { ElNotification, ElMessageBox, ElMessage } from 'element-plus'
import { getToken, parseJwt } from '@/utils/auth'

// 创建 axios 实例
export const service = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(config => {
  // 是否需要携带 Token
  const isToken = (config.headers || {}).isToken === false ? false : true
  if (isToken && getToken()) {
    config.headers['Authorization'] = 'Bearer ' + getToken()
  }

  // 处理 GET 请求参数
  if (config.method === 'get' && config.params) {
    const params = new URLSearchParams()
    for (const key in config.params) {
      const value = config.params[key]
      if (value !== null && value !== undefined) {
        params.append(key, value)
      }
    }
    config.url += '?' + params.toString()
    config.params = {}
  }

  return config
}, error => {
  console.error('请求拦截失败:', error)
  return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
  const code = res.data.code || 200
  const msg = res.data.msg || '系统异常'
  if (res.status === 304) {
    // 304 响应需要手动读取缓存数据
    const cachedData = JSON.parse(localStorage.getItem('cachedStudentData'));
    if (cachedData) {
      return Promise.resolve({ code: 200, data: cachedData });
    } else {
      return Promise.reject('缓存数据缺失');
    }
  }
  if (code === 401) {
    ElMessageBox.confirm(
      '登录状态已过期，请重新登录',
      '系统提示',
      { confirmButtonText: '重新登录', cancelButtonText: '取消', type: 'warning' }
    ).then(() => {
      // 直接跳转到登录页
      location.href = '/login'
    }).catch(() => {
      // 用户取消操作
    })
    return Promise.reject('无效的会话，请重新登录。')
  } else if (code !== 200) {
    ElMessage({ message: msg, type: 'error', duration: 5 * 1000 })
    return Promise.reject(new Error(msg))
  } else {
    return Promise.resolve(res.data)
  }
}, error => {
  let { message } = error
  if (message == "Network Error") {
    message = "后端接口连接异常"
  } else if (message.includes("timeout")) {
    message = "系统接口请求超时"
  } else if (message.includes("Request failed with status code")) {
    message = "系统接口" + message.substr(message.length - 3) + "异常"
  }
  ElMessage({ message: message, type: 'error', duration: 5 * 1000 })
  return Promise.reject(error)
})
